/*
 * Copyright (c) 2007 centrevillage <centrevillage@gmail.com>
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "WaveManager.h"

namespace wave {

using namespace boost;

mutex WaveManager::guard_;
mutex WaveManager::playGuard_;
mutex WaveManager::startEventGuard_;
mutex WaveManager::sendEventGuard_;

WaveManager::WaveManager() :
    waveOut_(65536, 4),
    fmt_(),
    pHost_(0),
    pTh_(0),
    isWorking_(false),
    initialBufSize_(0),
    startEventCounter_(0),
    sendEventCounter_(0),
    startEvents_(),
    sendEvents_()
{
    waveOut_.selectDevice(0);
    waveOut_.setBufLimit(3);
    waveOut_.setStartEventHandler(boost::bind(&WaveManager::fireStartEvent, this));
    waveOut_.setSendEventHandler(boost::bind(&WaveManager::fireSendEvent, this));
}

WaveManager::~WaveManager() {
}

void WaveManager::stop() {
    mutex::scoped_lock lock(playGuard_);
    waveOut_.stop();
    if (pTh_) {
        if (isWorking_) {
            mutex::scoped_lock lock(guard_);
        }
//        pTh_->join();
        delete pTh_;
        pTh_ = 0;
    }
}

bool WaveManager::playVsti() {
    mutex::scoped_lock lock(playGuard_);
    using namespace boost;
    if (isWorking_) return false;
    if (!pHost_) return false;
    if (!waveOut_.isOpen()) {
        if (!waveOut_.open(true)) return false;
    }

    isWorking_ = true;
    pTh_ = new thread(bind(&WaveManager::playVstiImpl, this));

    return true;
}

void WaveManager::playVstiImpl() {
    // TODO: 
    mutex::scoped_lock lock(guard_);
    WaveBuf outBuf;
    if (pHost_->process(outBuf)) {
        waveOut_.send(outBuf);
    }
    while (pHost_->process(outBuf)) {
        while (waveOut_.isFullBuf()) ::Sleep(100);
        if (waveOut_.isEnd()) {
//            pHost_->resetPlugins();
            break;
        }
        waveOut_.send(outBuf);
    }
    waveOut_.waitPlayEnd();
    waveOut_.close();
    isWorking_ = false;
}

void WaveManager::playInitial() {
//    if (initialBufSize_ <= 0) return;
    if (!waveOut_.isOpen()) {
        if (!waveOut_.open(true)) return;
    }
    waveOut_.sendFirst();
    // TODO:
}

int WaveManager::addStartEvent(SyncEventHandle handle) {
    mutex::scoped_lock lock(startEventGuard_);
    startEvents_.push_back(make_pair(++startEventCounter_, handle));
    return startEventCounter_;
}

bool WaveManager::delStartEvent(int id) {
    mutex::scoped_lock lock(startEventGuard_);
    EventHandlerList::iterator i = startEvents_.begin(), e = startEvents_.end();
    for (;i!=e;++i) {
        if (i->first == id) {
            startEvents_.erase(i);
            return true;
        }
    }
    return false;
}

void WaveManager::clearStartEvent() {
    mutex::scoped_lock lock(startEventGuard_);
    startEvents_.clear();
    startEventCounter_ = 0;
}

int WaveManager::addSendEvent(SyncEventHandle handle) {
    mutex::scoped_lock lock(sendEventGuard_);
    sendEvents_.push_back(make_pair(++sendEventCounter_, handle));
    return sendEventCounter_;
}

bool WaveManager::delSendEvent(int id) {
    mutex::scoped_lock lock(sendEventGuard_);
    EventHandlerList::iterator i = sendEvents_.begin(), e = sendEvents_.end();
    for (;i!=e;++i) {
        if (i->first == id) {
            sendEvents_.erase(i);
            return true;
        }
    }
    return false;
}

void WaveManager::clearSendEvent() {
    mutex::scoped_lock lock(sendEventGuard_);
    sendEvents_.clear();
    sendEventCounter_= 0;
}

void WaveManager::fireStartEvent() {
    mutex::scoped_lock lock(startEventGuard_);
    EventHandlerList::iterator i = startEvents_.begin(), e = startEvents_.end();
    for (;i!=e;++i) { (i->second)(); }
}

void WaveManager::fireSendEvent() {
    mutex::scoped_lock lock(sendEventGuard_);
    EventHandlerList::iterator i = sendEvents_.begin(), e = sendEvents_.end();
    for (;i!=e;++i) { (i->second)(); }
}


} // end of namespace wave
